import json

from django.shortcuts import render
from django.views import View

from django_redis import get_redis_connection
from django.http import HttpResponse,JsonResponse

from libs.captcha.captcha import captcha
from libs.aliyun_mail.alibabacloud_sample import cust
from random import randint

from apps.users.models import User
class ImagecodeView(View):
    def get(self,request,uuid):
        text,image=captcha.generate_captcha()
        redis_cli=get_redis_connection('code')
        redis_cli.setex(uuid,100,text)
        return HttpResponse(image,content_type='image/jpeg')

class SmsCodeView(View):
    def get(self,request,mobile):
        #接收数据
        image_code=request.GET.get('image_code')
        uuid=request.GET.get('image_code_id')
        #验证数据
        if not all([image_code,uuid]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        redis_cli=get_redis_connection('code')
        redis_image_code=redis_cli.get(uuid)
        if not redis_image_code:
            return JsonResponse({'code':400,'errmsg':'图片验证码已过期'})
        if redis_image_code.decode().lower()!=image_code:
            return JsonResponse({'code':400,'errmsg':'图片验证码错误'})

        #判断频繁发送
        send_flag=redis_cli.get('send_flag_%s'%mobile)
        if send_flag==1:
            return JsonResponse({'code':400,'errmsg':'请勿频繁获取验证码'})
        #生成短信验证码
        sms_code="%6d"%randint(0,999999)
        #保存短信验证码
        pipeline=redis_cli.pipeline()
        pipeline.setex(mobile,5*60,sms_code)
        pipeline.setex('send_flag_%s'%mobile,60,1)
        pipeline.execute()
        #发送短信验证码
        #cust.Sms.main([mobile,sms_code])
        from celery_tasks.sms.tasks import celery_send_sms_code
        celery_send_sms_code.delay(mobile,sms_code)
        #返回响应
        return JsonResponse({'code':200,'errmsg':'短信验证码已发送'})
class EmailVerifyView(View):
    def put(self,request):
        from utils.tools import decrypt

        params=request.GET
        data=decrypt(params.get('token'))
        id=data['id']
        try:
            user=User.objects.get(id=id)
        except:
            pass
        else:
            user.email_active=True
            user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})